<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\UserModel;
use cmf\controller\HomeBaseController;
use app\portal\model\ActivityModel;
use app\portal\model\ActivityUploadModel;
use app\portal\model\UserOrganizeModel;
use app\portal\model\UserRankModel;
use think\Request;
use think\Db;
use think\captcha\Captcha;


class IndexController extends HomeBaseController
{
    //社区积分信息
    public function community(){
        $rank=new UserRankModel();
        $data=$rank->with('user')->select();
        $list=[];
        foreach ($data as $k=>$v){
            @$list[$v['user']['community']]+=$v['all_points'];
        }
        unset($list[0]);
        unset($list['']);
        arsort($list);
        $list=array_slice($list,0,6,true);
        $array=[];
        foreach ($list as $k=>$v){
            $name=Db::name('community')->where('id',$k)->value('name');
            $a=[$name,$v];
            $array[]=$a;
        }
        //dump($array);
        return $array;
    }
    //团体积分信息
    public function group(){
        $rank=new UserRankModel();
        $data=$rank->with('user')->select();
        $list=[];
        foreach ($data as $k=>$v){
            @$list[$v['user']['group']]+=$v['all_points'];
        }
        unset($list[0]);
        unset($list['']);
        arsort($list);
        $list=array_slice($list,0,6,true);
        $array=[];
        foreach ($list as $k=>$v){
            $name=Db::name('organize_child')->where('id',$k)->value('name');
            $a=[$name,$v];
            $array[]=$a;
        }
        //dump($array);
        return $array;
    }
    public function index()
    {        
//        $str ="05:00" - "04:00";
//        echo $str;exit;
        $model=new ActivityModel();
        $rank=new UserRankModel();
        $user = session('user');
        //$user=Db::name('user')->where('id',$user_id)->field('user_nickname,avatar,create_time')->find();

        $this->assign('user',$user);
        return $this->fetch(':index');
    }
    //获取护学岗地图数据
    public function json_get_activity(){
        /*临时以最大值为最新活动*/
        /*1 牵手，2 啄木鸟 3 交管员*/
        $org_id = input('type/d',0);
        $lng=[];$lat=[];
        $result = [];
        $data=[];
        $location=[];
        try{
            if(!$org_id){
                throw new \Exception("组织类型缺失。");
            }
            //$id = Db::name('activity')->where('org_id',$org_id)->max('id');
            $org_id==1? $id=16:$id=Db::name('activity')->where('org_id',$org_id)->max('id');
            $activity_info = Db::name('activity')->field('id,title,point,place')->find($id);

     
            $location_coor = json_decode($activity_info['point']);
            $location_name = json_decode($activity_info['place']);
            if($location_coor){
                foreach ($location_coor as $k=>$v){
                    $cood_info = explode(',',$v);
                   
                    $point=[
                        'name' => $location_name[$k],
                        'cood' =>[
                            'lng'=>$cood_info[1],
                            'lat'=>$cood_info[0]
                        ]
                    ];
                    $location[]=$point;
                    $lat[]=$cood_info[0];
                    $lng[]=$cood_info[1];
                }
                $activity_info['location']=$location;
                unset($activity_info['place']);
                unset($activity_info['point']);
                $data['activity_info']=$activity_info;
                
                $activity_info['center']=[
                    "lat"=>(max($lat)+min($lat))/2,
                    "lng"=>(max($lng)+min($lng))/2
                    ];
            }else{
                 /*这是异常情况，数据原因，没有找到点的，默认为日照市交警队的地址*/
                $activity_info["center"]=[
                    "lat"=>35.425120,
                    "lng"=>119.537250
                ];
            }
            $result['error'] = false;
            $result['data'] = $activity_info;
            $result['errmsg'] = '最新活动信息获取成功';

        }catch(\Exception $e){
            $result["error"] =true;
            $result["errmsg"] = $e->getMessage();
        }
        
        
        return json($result);
    }
    //牵手地图
    public function qianshou_map(){
        return $this->fetch(':qianshou_map');
    }
    //大地图
    public function map(){
        return $this->fetch(':map');
    }
    //验证码
    public function captcha(){
        $config = [
            'codeSet' => '0123456789',
            'useCurve' => false,
            'length' => 4,
            'useNoise' => false,
            'expire'   => 1800,
            'fontSize' =>30
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    public function test(){
      $begin=mktime(0,0,0,date('m'),1,date('Y'));
    }


    //获取啄木鸟上传问题地点数据,一个自然月的数据
    public function zhuomu_map2(){
        $org_id=2;
        $model = new ActivityUploadModel();
        $begin=mktime(0,0,0,date('m'),1,date('Y'));
        $location=$model->where('org_id',$org_id)->where('ctime','>',$begin)->value('location');
        var_dump($model->getLastSql());exit;
        $place=$model->where('org_id',$org_id)->where('ctime','>',$begin)->column('place');
        $a=[];$b=[];$point=[];
        if($location){
            foreach ($location as $k=>$v){
                $point[]=explode(',',$v);
                $a[]=explode(',',$v)[0];
                $b[]=explode(',',$v)[1];
            }
            $c=(max($a)+min($a))/2;
            $d=(max($b)+min($b))/2;
            $center=[$c,$d];
            $res=['point'=>$point,'center'=>$center,'content'=>$place];
        }else{
            $res=['center'=>[119.518183,35.434015]];
        }
        return json($res);
    }
    //获取啄木鸟上传问题地点数据,一个自然月的数据
    public function zhuomu_map(){
        $org_id=2;
        $model = new ActivityUploadModel();
        $begin=mktime(0,0,0,date('m'),1,date('Y'));
        $location=$model->where('org_id',$org_id)->where('ctime','>',$begin)->column('location');
        $place=$model->where('org_id',$org_id)->where('ctime','>',$begin)->column('place');


        $a=[];$b=[];$point=[];
        if($location){
            foreach ($location as $k=>$v){
                $point[]=explode(',',$v);
                $a[]=explode(',',$v)[0];
                $b[]=explode(',',$v)[1];
            }
            $c=(max($a)+min($a))/2;
            $d=(max($b)+min($b))/2;
            $center=[$c,$d];
            $res=['point'=>$point,'center'=>$center,'content'=>$place];
        }else{
            $res=['center'=>[119.518183,35.434015]];
        }
        return json($res);
    }


    //报名申请
    public function apply_status(){
        $user=session('user');
        $org_id = input('org_id');
        $model=new UserOrganizeModel();
        if($user){
           $find=$model->where(['user_id'=>$user['id'],'org_id'=>$org_id])->find();
            if($find){
                if($find['status']==1){
                    $this->error('您已经是该类志愿者了，不需要在申请了!' ,'',2);
                }
                $this->error('您已提交申请!请耐心等待审核!','',2);
            }
        }
        $this->success('正在前往申请页面!', url('/portal/index/apply') ,'',2);
    }
    //报名申请
    public function apply(){
        return $this->fetch(':apply');
    }
    //填写资料
    public function do_info(){
        $model=new UserOrganizeModel();
        $user=session('user');
        $more=Db::name('user')->where('id',$user['id'])->value('more');
        if($user==null){
            return $this->fetch(':register');
        }elseif( $more==null){
            $this->success('正在前往完善信息页面~!', url('make_info'));
        }else{
            $find=$model->where(['user_id'=>$user['id']])->find();
            if($find){
                if($find['status']==1){
                    $this->error('您已经是志愿者了，不需要在申请了!', url('/'));
                }
                $this->error('您已提交申请!，请等待审核!', url('/'));
            }
        }
    }
    public function make_info(){
        $district=Db::name('community_district')->select();
        $group=Db::name('organize_child')->select();
        $org_id = input('org_id');
        $img=Db::name('slide_item')->where('slide_id',4)->select();
        $volunt_post=Db::name('volunt_post')->select();
        $this->assign('volunt_post',$volunt_post);
        $this->assign('img',$img);
        $this->assign('district',$district);
        $this->assign('org_id',$org_id);
        $this->assign('group',$group);
        return $this->fetch(':applyZcXq');
    }

    //获取数据
    public function get_big_team(){
        $data=Db::name('organize')->select();
        return json($data);
    }
    public function get_mid_team(){
        $id=input('id');
        $data=Db::name('organize_child')->where('org_id',$id)->select();
        return json($data);
    }

    //上传图片

    public function up_picture(Request $request){
        $file = $request->file('file');
        $info = $file->move('upload/portal');
        if($info){
            $path = '/upload/portal/'.$info->getSaveName();
            $path=str_replace('\\','/',$path);
            $data= ['url'=>$path];
            return json($data);
        }
    }

    //ajax检验身份证号
    function check_idcard($idcard){
        // 只能是18位
        if(strlen($idcard)!=18){
            return '长度不够';
        }
        // 取出本体码
        $idcard_base = substr($idcard, 0, 17);
        // 取出校验码
        $verify_code = substr($idcard, 17, 1);
        // 加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        // 校验码对应值
        $verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        // 根据前17位计算校验码
        $total = 0;
        for($i=0; $i<17; $i++){
            $total += substr($idcard_base, $i, 1)*$factor[$i];
        }
        // 取模
        $mod = $total % 11;
        // 比较校验码
        if($verify_code == $verify_code_list[$mod]){
            return '输入正确';
        }else{
            return '校验不通过';
        }
    }
    //保存资料
    public function save_info(){
        $model=new UserOrganizeModel();
        $data=input('post.');
        $result=[];
        try{
            if(!$data['user_nickname']){
                throw new \Exception('请填写用户昵称');
            }
            if(!$data['more']['idcard']){
                throw new \Exception('请填写身份证号');
            }
            $data['birthday']=strtotime(substr($data['more']['idcard'],6,8));
            if($data['more']['idcard'][-2]%2==1){
                $data['sex']=1;
            }else{
                $data['sex']=2;
            }
            if(!$data['big_team']){
                throw new \Exception('请选择大队');
            }
            if(!$data['avatar']){
                throw new \Exception('请上传头像~');
            }

            $user_id=cmf_get_current_user_id();
            $db= new UserModel();
            $data['more']=json_encode($data['more']);
            $res = $db->where('id',$user_id)->update($data);
            if ($res === false) {
                throw new \Exception('更新用户信息失败~');
            }
            $user=session('user');
            $user=array_replace($user,$data);
            session('user',$user);
            $sel=$model->where('user_id',$user['id'])->select();
            if (count($sel)>0) {
                throw new \Exception('请勿重复提交~');
            }
            $user_data=['user_id'=>$user['id'],
                'ctime'=>time(),
                'big_team'=>$data['big_team'],
                'mid_team'=>$data['mid_team']
            ];
            $model->insert($user_data);
            $result['error']=false;
            $result['msg']='修改信息并成功提交申请';
        }catch (\Exception $e){
            $result['error']=true;
            $result['msg']=$e->getLine().'行'.$e->getMessage();
        }
        return json($result);
    }
    //用户登录
    public function login(){
        return $this->fetch(':login');
    }

    //用户注册
    public function register(){
        return $this->fetch(':register');
    }
    //用户手机号绑定微信用户openid
    public function initializes(){
        //$this->user_id=cmf_get_current_user_id();
        $this->user_id=null;
        if(!$this->user_id){
            session('openid','123qwe');
            $openid = session('openid');
            if(!$openid){
                echo '获取';
            }else{
                $user=Db::name('user')->where('openid',$openid)->find();
                if(!$user){
                    echo '注册登录';
                }else{
                    unset($user['user_pass']);
                    dump($user);
                    session('user',$user);
                }
            }
        }else{
            $openid = session('openid');
            if(!$openid){
                echo '获取';
            }else{
                $user=Db::name('user')->where('openid',$openid)->find();
                if(!$user){
                    echo '绑定openid';
                }
            }
        }
    }
    public function another(){
        $openid = session('openid');
        if($openid){
            $user=Db::name('user')->where('openid',$openid)->find();
            if($user){
                unset($user['user_pass']);
                dump($user);
                session('user',$user);
            }else{
                $this->user_id=null;
                if($this->user_id){
                    echo '绑定';
                }else{
                    echo '注册登录';
                }
            }
        }else{
            echo '获取';
        }
    }
    public function user_find($id){
        $data=Db::name('user')->where('id',$id)->find();
        dump($data);
    }

    //获取志愿者风采详情
    public function volunt_content(){
        $id=input('id');
        $data=Db::name('slide_item')->where('id',$id)->find();
        return json($data);
    }
    public function tests(){
        $activity=Db::name('activity')->where('id',15)->field('end_date,org_id,max_people')->find();
        $org=$activity['org_id']==1?'牵手':'啄木鸟';
        dump($org);
        dump($activity);
//        $this->user_id=29;
//        $duration=3600;
//        $point_rule=Db::name('point_rule')->where('org_id',1)->find();
//        $rule=$point_rule['point']/$point_rule['num'];
//        $points=$duration/3600*$rule;
//        $user_rank=Db::name('user_rank')->where('user_id',$this->user_id)->find();
//        if($user_rank){
//            $user_rank['duration']=$user_rank['duration']+$duration;
//            $user_rank['q_times']=$user_rank['q_times']+1;
//            $user_rank['all_points']=$user_rank['all_points']+ $points;
//            $user_rank['can_points']=$user_rank['can_points']+ $points;
//            Db::name('user_rank')->update($user_rank);
//        }else{
//            Db::name('user_rank')->insert(['user_id'=>$this->user_id,'duration'=>$duration,'q_times'=>1,'all_points'=>$points,'can_points'=>$points]);
//        }


        exit;
        //$point_rule=Db::name('point_rule')->where('org_id',1)->value('num');


        //$points=$duration/3600/$point_rule;




//        $can_time=date("H:i",time()+15*60);
//        dump($can_time);exit;

//        $model=new UserOrganizeModel();
//        $user_data[]=['user_id'=>1,'org_id'=>1,'child_id'=>1,'ctime'=>time()];
//        $ins=$model->insertAll($user_data);
//        dump($ins);
//        $result=[];
//        try{
//           Db::query('update cmf_user_rank set can_points = 0;');
//            $result["error"]= false;
//            $result['msg']='success';
//        }catch (\Exception $e){
//            $result["error"]= true;
//            $result['msg']= $e->getMessage();
//        }
//
//      return json($result);
    }

}
